﻿Imports System.Net
Imports System.Text
Imports System.Collections.Specialized
Imports System.Net.HttpRequestHeader
Imports System.ComponentModel

Public Class TCDClient
    Inherits WebClient

    Private _CookieContainer As New CookieContainer()
    Private _Referer As String = "http://daotao.vimaru.edu.vn/tracuudiem"

    Public Sub New()
        Headers.Add("Accept-Language: vi-VN,vi;q=0.8,fr-FR;q=0.6,fr;q=0.4,en-US;q=0.2,en;q=0.2")
        Headers.Add("Accept-Charset: windows-1258,utf-8;q=0.7,*;q=0.3")
    End Sub

    Protected Overrides Function GetWebRequest(ByVal address As Uri) As WebRequest
        Dim request As WebRequest = MyBase.GetWebRequest(address)
        If TypeOf request Is HttpWebRequest Then
            With TryCast(request, HttpWebRequest)
                .CookieContainer = _CookieContainer
                .UserAgent = "TCDClient"
                .Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
                .AutomaticDecompression = DecompressionMethods.Deflate Or DecompressionMethods.GZip
                If .Method = "POST" Then
                    .KeepAlive = True
                    .ServicePoint.Expect100Continue = False
                    .Referer = _Referer
                End If
            End With
        End If
        Return request
    End Function

    Public Function Download(ByVal url As String, ByVal ret As Integer, ByVal ParamArray arg() As String) As Object
        Dim response As Byte()

        If arg.Length = 0 Then
            response = DownloadData(url)
        Else
            Dim Data As New NameValueCollection()
            For i As Integer = 0 To arg.Length - 2 Step 2
                Data.Add(arg(i), arg(i + 1))
            Next
            response = UploadValues(url, "POST", Data)
        End If

        Select Case ret
            Case 0
                Return Encoding.ASCII.GetString(ResponseHeaders.ToByteArray())
            Case 1
                Return Encoding.ASCII.GetString(response)
            Case 2
                Return Encoding.UTF8.GetString(response)
            Case 3
                Return response
        End Select

        Return Nothing
    End Function
End Class
